<!-- 商家销量统计的横向柱状图 -->
<template>
  <div class="com-container">
      <div class="com-chart" ref="seller_ref" ></div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data () {
    return {
      chartInstance: null,
      allData: [],
      currPage: 1,
      totalPage: 0,
      timeId: null
    }
  },
  created () { // 组件创建后 - 函数
    // 组件创建时，注册socket的回调函数
    this.$socket.registerCallBack('sellerData', this.getData)
  },
  mounted () { // 组件挂载后 - 函数
    this.initChart()
    // this.getData()
    // 发送数据给服务器，告诉服务器，这个客户端需要数据
    this.$socket.send({
      action: 'getData',
      socketType: 'sellerData',
      chartName: 'seller',
      value: ''
    })
    this.resizeChart()
    window.addEventListener('resize', this.resizeChart)
  },
  destroyed () { // 组件销毁时 - 函数
    // 组件销毁时清掉定时器
    this.clearInterval()
    // 组件销毁时移除监听器
    window.removeEventListener('resize', this.resizeChart)
    // 组件销毁时，注销socket的回调函数
    this.$socket.unregisterCallBack('sellerData')
  },
  methods: {
    // 1.初始化echartsInstance对象
    initChart () {
      this.chartInstance = this.$echarts.init(this.$refs.seller_ref, this.theme)
      const initOption = {
        title: {
          text: '┃ 商家销售统计',
          left: 20,
          top: 20
        },
        grid: {
          top: '20%',
          left: '3%',
          bottom: '3%',
          right: '6%',
          containLabel: true // 距离包含坐标轴上的文字
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            z: 0, // 调整层级
            lineStyle: {
              color: '#2d3443'
            }
          }
        },
        series: [
          {
            type: 'bar',
            label: {
              show: true,
              position: 'right',
              textStyle: {
                color: '#FFF'
              }
            },
            itemStyle: {
              color: new this.$echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { // 0%状态下的颜色值
                  offset: 0,
                  color: '#5052ee'
                },
                { // 100%状态下的颜色值
                  offset: 1,
                  color: '#ab6ee5'
                }
              ])
            }
          }
        ]
      }
      this.chartInstance.setOption(initOption)
    },

    // 2.获取服务器端数据
    getData (res) {
      // 获取seller数据 /api/seller
      // const { data: res } = await this.$http.get('seller')
      this.allData = res
      this.allData.sort((a, b) => a.value - b.value)
      this.totalPage = this.allData.length % 5 === 0 ? this.allData.length / 5 : this.allData.length / 5 + 1
      this.updateChart()
      this.setInterval()
    },

    // 3.更新图表
    updateChart () {
      const newData = this.allData.slice((this.currPage - 1) * 5, (this.currPage - 1) * 5 + 5)
      const sellerNames = newData.map((item) => {
        return item.name
      })
      const sellerValues = newData.map((item) => {
        return item.value
      })

      const dataOption = {
        yAxis: {
          data: sellerNames
        },
        series: [
          {
            data: sellerValues
          }
        ]
      }
      this.chartInstance.setOption(dataOption)
    },

    // 4.分辨率适配
    resizeChart () {
      const FontSize = this.$refs.seller_ref.offsetWidth / 100 * 3.6
      const resizeOption = {
        title: {
          textStyle: {
            fontSize: FontSize
          }
        },
        tooltip: {
          axisPointer: {
            lineStyle: {
              width: FontSize
            }
          }
        },
        series: [
          {
            barWidth: FontSize,
            itemStyle: {
              barBorderRadius: [0, FontSize / 2, FontSize / 2, 0]
            }
          }
        ]
      }
      this.chartInstance.setOption(resizeOption)
      this.chartInstance.resize()
    },

    // 6.定时刷新图表
    setInterval () {
      this.timeId = setInterval(() => {
        this.currPage++
        if (this.currPage >= this.totalPage) {
          this.currPage = 1
        }
        this.updateChart()
      }, 3000)
    },

    // 7.清除定时器
    clearInterval () {
      this.timeId = null
    }
  },
  computed: {
    ...mapState(['theme'])
  },
  watch: {
    theme () {
      console.log('主题切换了')
      // 1.销毁当前图表
      this.chartInstance.dispose()
      // 2.重新注册当前图表 -- 以最新主题渲染图表
      this.initChart()
      this.resizeChart()
      this.updateChart()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
